<template>
  <div class="register-container">
    <div class="max-w-md w-full bg-white rounded-lg shadow-md overflow-hidden">
      <div class="px-6 py-8">
        <h2 class="text-center text-3xl font-bold text-gray-800 mb-6">用户注册</h2>
        
        <form @submit.prevent="handleRegister">
          <div class="mb-4">
            <label for="username" class="block text-gray-700 text-sm font-medium mb-2">用户名</label>
            <input 
              id="username"
              v-model="registerForm.username" 
              type="text" 
              class="form-input"
              placeholder="请输入用户名"
              required
            />
            <p v-if="errors.username" class="mt-1 text-sm text-red-600">{{ errors.username }}</p>
          </div>
          
          <div class="mb-4">
            <label for="nickname" class="block text-gray-700 text-sm font-medium mb-2">昵称</label>
            <input 
              id="nickname"
              v-model="registerForm.nickname" 
              type="text" 
              class="form-input"
              placeholder="请输入昵称"
              required
            />
            <p v-if="errors.nickname" class="mt-1 text-sm text-red-600">{{ errors.nickname }}</p>
          </div>
          
          <div class="mb-4">
            <label for="password" class="block text-gray-700 text-sm font-medium mb-2">密码</label>
            <input 
              id="password"
              v-model="registerForm.password" 
              type="password" 
              class="form-input"
              placeholder="请输入密码"
              required
            />
            <p v-if="errors.password" class="mt-1 text-sm text-red-600">{{ errors.password }}</p>
          </div>
          
          <div class="mb-4">
            <label for="confirmPassword" class="block text-gray-700 text-sm font-medium mb-2">确认密码</label>
            <input 
              id="confirmPassword"
              v-model="registerForm.confirmPassword" 
              type="password" 
              class="form-input"
              placeholder="请再次输入密码"
              required
            />
            <p v-if="errors.confirmPassword" class="mt-1 text-sm text-red-600">{{ errors.confirmPassword }}</p>
          </div>
          
          <div class="mb-4">
            <label for="email" class="block text-gray-700 text-sm font-medium mb-2">邮箱</label>
            <input 
              id="email"
              v-model="registerForm.email" 
              type="email" 
              class="form-input"
              placeholder="请输入邮箱"
              required
            />
            <p v-if="errors.email" class="mt-1 text-sm text-red-600">{{ errors.email }}</p>
          </div>
          
          <div class="mb-6">
            <label for="phone" class="block text-gray-700 text-sm font-medium mb-2">手机号码</label>
            <input 
              id="phone"
              v-model="registerForm.phone" 
              type="text" 
              class="form-input"
              placeholder="请输入手机号码"
            />
            <p v-if="errors.phone" class="mt-1 text-sm text-red-600">{{ errors.phone }}</p>
          </div>
          
          <div v-if="errors.general" class="mb-4 p-3 bg-red-100 text-red-700 rounded-md">
            {{ errors.general }}
          </div>
          
          <div class="mb-6">
            <button 
              type="submit" 
              class="w-full btn-primary"
              :disabled="isLoading"
            >
              <span v-if="isLoading">注册中...</span>
              <span v-else>注册</span>
            </button>
          </div>
          
          <div class="text-center text-sm">
            已有账号？
            <router-link to="/login" class="text-primary hover:underline">立即登录</router-link>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const isLoading = ref(false)

const registerForm = reactive({
  username: '',
  nickname: '',
  password: '',
  confirmPassword: '',
  email: '',
  phone: '',
})

const errors = reactive({
  username: '',
  nickname: '',
  password: '',
  confirmPassword: '',
  email: '',
  phone: '',
  general: ''
})

const validateForm = () => {
  let isValid = true
  errors.username = ''
  errors.nickname = ''
  errors.password = ''
  errors.confirmPassword = ''
  errors.email = ''
  errors.phone = ''
  errors.general = ''
  
  if (!registerForm.username) {
    errors.username = '请输入用户名'
    isValid = false
  } else if (registerForm.username.length < 3 || registerForm.username.length > 20) {
    errors.username = '用户名长度应为3-20个字符'
    isValid = false
  }
  
  if (!registerForm.nickname) {
    errors.nickname = '请输入昵称'
    isValid = false
  }
  
  if (!registerForm.password) {
    errors.password = '请输入密码'
    isValid = false
  } else if (registerForm.password.length < 6 || registerForm.password.length > 20) {
    errors.password = '密码长度应为6-20个字符'
    isValid = false
  }
  
  if (!registerForm.confirmPassword) {
    errors.confirmPassword = '请再次输入密码'
    isValid = false
  } else if (registerForm.confirmPassword !== registerForm.password) {
    errors.confirmPassword = '两次输入密码不一致'
    isValid = false
  }
  
  if (!registerForm.email) {
    errors.email = '请输入邮箱'
    isValid = false
  } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(registerForm.email)) {
    errors.email = '请输入有效的邮箱地址'
    isValid = false
  }
  
  if (registerForm.phone && !/^1[3-9]\d{9}$/.test(registerForm.phone)) {
    errors.phone = '请输入有效的手机号码'
    isValid = false
  }
  
  return isValid
}

const handleRegister = async () => {
  if (!validateForm()) return;
  
  isLoading.value = true;
  errors.general = '';
  
  console.log('注册表单数据:', registerForm);
  console.log('发送注册请求...');
  
  try {
    // 发送注册请求
    const response = await fetch('/api/auth/register', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: registerForm.username,
        password: registerForm.password,
        nickname: registerForm.nickname,
        email: registerForm.email,
        phone: registerForm.phone || null
      })
    });
    
    console.log('注册响应状态:', response.status);
    
    // 解析响应数据
    const responseText = await response.text();
    console.log('注册响应文本:', responseText);
    
    let data;
    try {
      data = JSON.parse(responseText);
      console.log('注册响应数据:', data);
    } catch (e) {
      console.error('解析响应JSON失败:', e);
      if (response.ok) {
        // 如果状态码是成功的，但解析JSON失败，可能是返回了空数据或非JSON数据
        // 我们仍然认为注册成功
        alert('注册成功，请登录');
        router.push('/login');
        return;
      } else {
        throw new Error('服务器返回的数据格式不正确');
      }
    }
    
    if (!response.ok) {
      if (data && data.message && data.message.includes('用户名已存在')) {
        errors.username = '该用户名已被注册，请使用其他用户名';
      } else {
        throw new Error(data.message || '注册失败，请稍后再试');
      }
    } else {
      // 注册成功，显示成功消息并跳转到登录页
      alert(`注册成功！用户名: ${registerForm.username}，请登录`);
      router.push('/login');
    }
  } catch (error) {
    console.error('注册错误:', error);
    errors.general = error.message || '注册失败，请稍后再试';
  } finally {
    isLoading.value = false;
  }
};
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 1rem;
}
</style> 